package com.kecheng.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class TimeUtil {
	/**
	 * 获取本周周几的日期
	 * weekDay=0，表示周一
	 * @return
	 */
	public static Date getWeekDate(Integer weekDay){
		Calendar cal = Calendar.getInstance();
		cal.set(cal.DAY_OF_WEEK, cal.MONDAY);
		cal.set(Calendar.DATE, cal.get(cal.DATE) + weekDay);
		Date date = cal.getTime();
		return date;
	}
	/**
	 * 传入时间格式，和毫秒数，获取对应的时间转化
	 *
	 * @return
	 */
	public static String getString(String timeFormat, Long ms) {
		SimpleDateFormat sdf = new SimpleDateFormat(timeFormat);
		return sdf.format(ms);
	}

	/**
	 * 传入格式和日期得到相应的时间转化
	 * 
	 * @return
	 */
	public static String getString(String timeFormat, Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat(timeFormat);
		return sdf.format(date);
	}

	/**
	 * 传入格式，获取当前时间相应格式的时间转化
	 * 
	 * @return
	 */
	public static String getString(String timeFormat) {
		return getString(timeFormat, new Date());
	}

	/**
	 * 推迟和提前多少天(字符串)
	 * @param time 字符串时间
	 * @param days 推迟多少天（提前就是负数）
	 * @return
	 */
	public static String pulloff(String timeFormat,String time,int days){
		
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(timeFormat);
			Date date = sdf.parse(time);
			Calendar calendar = new GregorianCalendar();
			calendar.setTime(date);
			calendar.add(calendar.DAY_OF_YEAR, days);// 把日期往后增加一天.整数往后推,负数往前移动
			date = calendar.getTime();
			return sdf.format(date);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}
	/**
	 * 推迟和提前多少天(毫秒数)
	 * @param timeFormat（时间格式）
	 * @param ms 毫秒数
	 * @param days 推迟的天数（负数则为提前的天数）
	 * @return
	 */
	public static long pulloff(String timeFormat,Long ms,int days){
		try {
			Date date = new Date(ms);
			Calendar calendar = new GregorianCalendar();
			calendar.setTime(date);
			calendar.add(calendar.DAY_OF_YEAR, days);// 把日期往后增加一天.整数往后推,负数往前移动
			date = calendar.getTime();
			return date.getTime();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return 0L;
	}
	/**
	 * 计算两个字符串时间相差多少天
	 */
	public static int twoTimeDiff(String timeFormat, String time1,String time2){
		SimpleDateFormat sdf = new SimpleDateFormat(timeFormat);
		int days = 0;
		try {
			Date time11 = sdf.parse(time1);
			Date time22 = sdf.parse(time2);
			days = (int)((time22.getTime()-time11.getTime())/(24*60*60*1000));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return days;
	}
	
	/**
	 * 计算某个时间距离当天前时间的天数
	 */
	public static int oneTimeNow(String timeFormat,String time1){
		SimpleDateFormat sdf = new SimpleDateFormat(timeFormat);
		int days = 0;
		try {
			Date time11 = sdf.parse(time1);
			days = (int)((new Date().getTime()-time11.getTime())/(24*60*60*1000));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return days;
	}
	
}
